#include "executelogdlg.h"
#include "router/systemMonitor/timedTask/executelogdetaildlg.h"
#include "ui_executelogdlg.h"

ExecuteLogDlg::ExecuteLogDlg(QList<DictData> sys_job_group,QString id,QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ExecuteLogDlg)
{
    ui->setupUi(this);
    setWindowIcon(QIcon(":/image/res/stm.jpg"));
    //图标
    QPixmap pix(":/image/res/search.jpg");
    pix.scaled(25,25);
    ui->btn_hideSearch->setIcon(pix);
    ui->btn_search->setIcon(pix);
    QPixmap freshPix(":/image/res/refresh.jpg");
    ui->btn_reset->setIcon(freshPix.scaled(25,25));
    ui->btn_refresh->setIcon(freshPix.scaled(25,25));
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);

    this->sys_job_group = sys_job_group;
    this->id = id;

    init();

    //隐藏搜索
    connect(ui->btn_hideSearch,&QPushButton::clicked,this,[=](){
        ui->widget_2->setHidden(!ui->widget_2->isHidden());
    });
    //    //下一页
    connect(ui->btn_next,&QPushButton::clicked,this,[=](){
        ui->btn_next->setEnabled(0);
        currentPage ++;
        getList();
        initTable();
        initPageInfo();
    });
    //上一页
    connect(ui->btn_pervious,&QPushButton::clicked,this,[=](){
        ui->btn_pervious->setEnabled(0);
        currentPage --;
        getList();
        initTable();
        initPageInfo();
    });
    //跳转页
    connect(ui->lineEdit_gotoPage,&QLineEdit::returnPressed,this,[=](){
        int page = ui->lineEdit_gotoPage->text().toInt();
        ui->lineEdit_gotoPage->clear();
        if(page < 1 || page > totalPage){
            ui->lineEdit_gotoPage->setStyleSheet("border:1px solid red;");
            return;
        }
        ui->lineEdit_gotoPage->setStyleSheet("");
        currentPage = page;
        getList();
        initTable();
        initPageInfo();
    });
    //    重置
    connect(ui->btn_reset,&QPushButton::clicked,this,[=](){
        ui->btn_reset->setEnabled(0);
        init();
        ui->btn_reset->setEnabled(1);
    });
    //搜索
    connect(ui->btn_search,&QPushButton::clicked,this,[=](){
        getList();
        initTable();
        initPageInfo();
    });
    //刷新
    connect(ui->btn_refresh,&QPushButton::clicked,this,[=](){
        getList();
        initTable();
        initPageInfo();
    });
    connect(ui->btn_clean,&QPushButton::clicked,this,[=](){
        int flag = QMessageBox::question(0,"提示","是否确认清空所有调度日志数据项？",QMessageBox::Yes|QMessageBox::No);
        if(flag == QMessageBox::No) return;
        QByteArray *bytes = api.clean();
        QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
        if(200 == obj.value("code").toInt()){
            QMessageBox::warning(0,"提示",obj.value("msg").toString());
            getList();
            initTable();
            initPageInfo();
        }
    });
    //导出
    connect(ui->btn_export,&QPushButton::clicked,this,[=](){
        utils.exportExcel(ui->tableWidget,"定时任务日志表格");
    });
}

ExecuteLogDlg::~ExecuteLogDlg()
{
    delete ui;
}

void ExecuteLogDlg::init()
{
    if(!id.isEmpty()){
        QByteArray *data = api.getById(id.toLongLong());
        QJsonObject obj = QJsonDocument::fromJson(*data).object();
        QJsonObject jsonJob = obj.value("data").toObject();
        job = Job::toJob(jsonJob);
    }
    getDictList();
    initSearchArea();
    getList();
    initTable();
    initPageInfo();
}

void ExecuteLogDlg::getDictList()
{
    sys_common_status.clear();
    QByteArray *data = utils.getDictType("sys_common_status");
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray arr = obj.value("data").toArray();
    for(int i = 0;i< arr.size();i++){
        sys_common_status.append(DictData::toDictData(arr.at(i).toObject()));
    }
}

void ExecuteLogDlg::initSearchArea()
{
    ui->lineEdit_jobName->clear();
    ui->comboBox_executeStatus->clear();
    ui->comboBox_executeStatus->addItem("");
    for(int i = 0;i< sys_common_status.size();i++){
        ui->comboBox_executeStatus->addItem(sys_common_status.at(i).dictLabel,sys_common_status.at(i).dictValue);
    }
    ui->comboBox_jobGroup->clear();
    ui->comboBox_jobGroup->addItem("");
    for(int i = 0;i< sys_job_group.size();i++){
        ui->comboBox_jobGroup->addItem(sys_job_group.at(i).dictLabel,sys_job_group.at(i).dictValue);
    }
    ui->dateEdit_start->setDate(QDate(2000,1,1));
    ui->dateEdit_end->setDate(QDate(2000,1,1));
    if(!id.isEmpty()){
        ui->lineEdit_jobName->setText(job.jobName);
        for (int i = 0; i < ui->comboBox_jobGroup->count(); ++i) {
            if(job.jobGroup == ui->comboBox_jobGroup->itemData(i)){
                ui->comboBox_jobGroup->setCurrentIndex(i);
            }
        }
    }
    Job nullJob;
    this->job = nullJob;
    id = "";
}

void ExecuteLogDlg::getList()
{
    logList.clear();
    QString jobName = ui->lineEdit_jobName->text();
    QString status = ui->comboBox_executeStatus->currentData().value<QString>();
    QString taskGroup = ui->comboBox_jobGroup->currentData().value<QString>();
    QString start = ui->dateEdit_start->text();
    QString end = ui->dateEdit_end->text();
    QByteArray *data = api.logList(currentPage,pageSize,jobName,taskGroup,status,start,end);
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray arr = obj.value("rows").toArray();
    total = obj.value("total").toInt();
    for(int i = 0;i< arr.size();i++){
        logList.append(JobLog::toJobLog(arr.at(i).toObject()));
    }
    if(total%pageSize == 0){
        totalPage = total / pageSize;
    }else{
        totalPage = total / pageSize + 1;
    }
    ui->label_count->setText("共"+QString::number(total)+"条");
}

void ExecuteLogDlg::initTable()
{
    ui->tableWidget->setSortingEnabled(0);
    ui->tableWidget->sortByColumn(-1, Qt::AscendingOrder);
    ui->tableWidget->clear();
    QStringList columnHeader;
    columnHeader << "日志编号" << "任务名称" << "任务组名" << "调用目标字符串" << "日志信息" << "执行状态" << "执行时间" << "操作";
    ui->tableWidget->setColumnCount(columnHeader.size());
    ui->tableWidget->setHorizontalHeaderLabels(columnHeader);
    ui->tableWidget->setRowCount(logList.size());
    ui->tableWidget->setColumnWidth(0,70);
    ui->tableWidget->setColumnWidth(1,200);
    ui->tableWidget->setColumnWidth(3,240);
    ui->tableWidget->setColumnWidth(4,200);
    for(int i = 0;i< logList.size();i++){
        ui->tableWidget->setRowHeight(i,38);
        QString id = QString::number(logList.at(i).jobLogId);
        ui->tableWidget->setItem(i,0,new QTableWidgetItem(id));
        ui->tableWidget->setItem(i,1,new QTableWidgetItem(logList.at(i).jobName));
        QString group;
        for (int j = 0; j < sys_job_group.size(); ++j) {
            if(sys_job_group.at(j).dictValue == logList.at(i).jobGroup){
                group = sys_job_group.at(j).dictLabel;
                break;
            }
        }
        ui->tableWidget->setItem(i,2,new QTableWidgetItem(group));
        ui->tableWidget->setItem(i,3,new QTableWidgetItem(logList.at(i).invokeTarget));
        ui->tableWidget->setItem(i,4,new QTableWidgetItem(logList.at(i).jobMessage));
        ui->tableWidget->setItem(i,6,new QTableWidgetItem(logList.at(i).createTime));

        QLabel *statusLabel = new QLabel();
        statusLabel->setFixedSize(46,20);
        statusLabel->setAlignment(Qt::AlignCenter);
        for (int j = 0; j < sys_common_status.size(); ++j) {
            if(logList.at(i).status == sys_common_status.at(j).dictValue){
                statusLabel->setText(sys_common_status.at(j).dictLabel);
                statusLabel->setStyleSheet(utils.backShowStyle[sys_common_status.at(j).listClass]);
                break;
            }
        }
        QWidget *widget = new QWidget();
        QHBoxLayout* hLayout = new QHBoxLayout(widget);
        statusLabel->setAlignment(Qt::AlignCenter);
        hLayout->addWidget(statusLabel);
        ui->tableWidget->setCellWidget(i,5,widget);

        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout();
        QPushButton *btnDetail = new QPushButton;
        connect(btnDetail,&QPushButton::clicked,this,[=](){
            ExecuteLogDetailDlg *a = new ExecuteLogDetailDlg(logList.at(i));
            a->setAttribute(Qt::WA_DeleteOnClose);
            a->exec();
        });
        btnDetail->setText("详细");
        btnDetail->setFixedSize(60,23);
        btnDetail->setIcon(QIcon(":/svg/res/svg/eye-open.svg"));
        btnDetail->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(232, 244, 255);color: black;}QPushButton:hover {background-color: rgb(24, 144, 255);}QPushButton:pressed {background-color: rgb(24, 144, 200);}");
        tmp_layout->addWidget(btnDetail);
        tmp_widget->setLayout(tmp_layout);
        tmp_layout->setContentsMargins(0,0,0,0);
        ui->tableWidget->setCellWidget(i,7,tmp_widget);
    }
    // 设置单元格内容居中对齐
    for (int row = 0; row < ui->tableWidget->rowCount(); ++row) {
        for (int column = 0; column < ui->tableWidget->columnCount(); ++column) {
            QTableWidgetItem* item = ui->tableWidget->item(row, column);
            if (item) {
                item->setTextAlignment(Qt::AlignCenter);
            }
        }
    }
    ui->tableWidget->setSortingEnabled(1);
}

void ExecuteLogDlg::initPageInfo()
{
    if(currentPage == 1){
        ui->btn_pervious->setEnabled(0);
    }else{
        ui->btn_pervious->setEnabled(1);
    }
    ui->label_currentPage->setText(QString::number(currentPage));
    if(currentPage == totalPage){
        ui->btn_next->setEnabled(0);
    }else{
        ui->btn_next->setEnabled(1);
    }
}


void ExecuteLogDlg::on_btn_close_clicked()
{
    close();
}


void ExecuteLogDlg::on_btn_delete_clicked()
{
    QList<QTableWidgetItem*> items = ui->tableWidget->selectedItems();
    if(items.size() == 0) return;
    int rowCount = items.size() / 6;    //选中的行数
    QString ids;
    for(int i = 0;i< rowCount;i++){
        int index = ui->tableWidget->row(items.at(i * 6));
        if(i != rowCount - 1){
            ids += ui->tableWidget->item(index,0)->text() + ",";
        }else{
            ids += ui->tableWidget->item(index,0)->text();
        }
    }
    int flag = QMessageBox::question(0,"提示","确定删除所选项吗?",QMessageBox::Yes|QMessageBox::No);
    if(flag == QMessageBox::No) return;
    QByteArray *bytes = api.deleteLogItems(ids);
    QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
    if(200 == obj.value("code").toInt()){
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
        getList();
        initTable();
        initPageInfo();
    }
}


void ExecuteLogDlg::on_comboBox_pageItem_currentIndexChanged(int index)
{
    switch (index) {
    case 0:
        pageSize = 5;
        break;
    case 1:
        pageSize = 10;
        break;
    case 2:
        pageSize = 20;
        break;
    case 3:
        pageSize = 50;
        break;
    case 4:
        pageSize = 100;
        break;
    default:
        break;
    }
    currentPage = 1;
    getList();
    initTable();
    initPageInfo();
}

